'use strict';

const { Service } = require('ee-core');
const Ps = require("ee-core/ps");
const Conf = require("ee-core/config");
const path = require("path");
const Addon = require("ee-core/addon");

/**
 * 示例服务（service层为单例）
 * @class
 */
class HomeService extends Service {

  constructor(ctx) {
    super(ctx);
  }

  /**
   * openWindow
   */
  async openWindow(args) {
    const { content, windowName, windowTitle } = args
    let opt = {
      title: windowTitle,
      center: true,
      autoHideMenuBar: true
    }

    let addr = 'http://localhost:8080'
    let contentUrl = null
    if (Ps.isProd()) {
      const mainServer = Conf.getValue('mainServer');
      if (Conf.isFileProtocol(mainServer)) {
        addr = mainServer.protocol + path.join(Ps.getHomeDir(), mainServer.indexPath);
      } else {
        addr = mainServer.protocol + mainServer.host + ':' + mainServer.port;
      }
    }

    contentUrl = addr + content;

    const win = Addon.get('window').create(windowName, opt);
    const winContentsId = win.webContents.id;

    await win.loadURL(contentUrl)
    win.on('ready-to-show', () => {
      win.show()
    })

    win.webContents.on('before-input-event', (event, input) => {
      if (input.alt) {
        event.preventDefault(); // 阻止默认行为
      }
    });

    return winContentsId
  }
}

HomeService.toString = () => '[class HomeService]';
module.exports = HomeService;